package com.gaga.console.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gaga.common.result.AiModelApiResult;
import com.gaga.common.result.AiModelResult;
import com.gaga.console.base.service.impl.SuperServiceImpl;
import com.gaga.console.base.utils.RestUtils;
import com.gaga.console.core.entity.BvAiModel;
import com.gaga.console.core.entity.dto.ChatDto;
import com.gaga.console.core.mapper.BvAiModelMapper;
import com.gaga.console.core.service.BvAiModelService;
import com.gaga.console.core.service.impl.ai.AiFactory;
import com.gaga.console.core.service.impl.ai.AiHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author liujia
 * @since 2025-04-06
 */
@Slf4j
@Service
public class BvAiModelServiceImpl extends SuperServiceImpl<BvAiModelMapper, BvAiModel> implements BvAiModelService {

    @Override
    @Deprecated
    public String chat(ChatDto dto) {

        BvAiModel model = getById(dto.getModelId());
        if (model == null) {
            throw new RuntimeException("模型不存在");
        }
        //todo 这里有问题
        Map<String, Object> params = JSON.parseObject(model.getPolishPrompt(), Map.class);
        params.put("model", model.getModelCode());
        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("role", "user");
        contentMap.put("content", "我的直播间是" + dto.getLiveRoomDesc() + "，帮我润色下下面的话术，直接返回一条话术，可以直接用于tts转语音使用，并屏蔽" + dto.getBlockWords() + "，需要润色的话术是：" + dto.getMessage());
        params.put("messages", Arrays.asList(contentMap));

        Map<String, Object> headMap = new HashMap<>();
        headMap.put("Authorization", dto.getToken());
        headMap.put("Content-Type", "application/json");

        String restResult = RestUtils.post(model.getModelUrl(), params, headMap);
        log.info("===post result:{}", restResult);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = null;
        try {
            root = mapper.readTree(restResult);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        // 通过路径提取 content
        JsonNode contentNode = root
                .path("choices")
                .get(0)
                .path("message")
                .path("content");

        if (!contentNode.isMissingNode()) {
            return contentNode.asText();
        }
        return dto.getMessage();
    }

    @Override
    public AiModelResult callWithMessage(ChatDto dto) throws Exception {
        AiModelResult aiModelResult = new AiModelResult();
        BvAiModel biModel = getById(dto.getModelId());
        String polishPrompt = "";
        if (biModel != null) {
            polishPrompt = biModel.getPolishPrompt();
        }
        AiHandler handler = AiFactory.getHandler(dto, polishPrompt);
        AiModelApiResult aiModelApiResult = handler.getAiOutMessage(dto);
        if (!aiModelApiResult.getIsSuceess()) {
            aiModelResult.setIsSuceess(false);
            aiModelResult.setResult(aiModelApiResult.getResult());
            return aiModelResult;
        }
        aiModelResult.setResult(aiModelApiResult.getResult());
        return aiModelResult;
    }

}
